<?php
declare (strict_types = 1);

namespace app\week\controller;

use app\adminapi\extend\tools\excel\Excel;
use app\common\Qiniu;
use think\facade\Db;
use think\Request;
use think\facade\View;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\exception\ValidateException;
use think\facade\Filesystem;

class Week
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $data = Db::table('dept')->field('id,parent_id,dept_name')->select()->toArray();
        $data = recursionHandleData($data);
        View::assign(['data' => $data]);
        return  View::fetch();
        //
    }

    /**
     * 获取用户列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserList(){
        $data = Db::table('user')->field('id,user_name,phonenumber')->select()->toArray();
        return json(['code' => 0,'data' => $data,'msg' => 'ok']);
    }

    public function export(){
        // 设置表格的表头数据
        $header = ["A1" => "编号", "B1" => "姓名", "C1" => "年龄"];
        // 假设下面这个数组从数据库查询出的二维数组
        $data = [
            [1,'张耀',18],
            [2,'柴彪',19],
            [3,'冯宝杰',22],
            [4,'戎飞',19],
            [5,'海豹',17]
        ];
        $data = Db::table('user')->field('id,user_name,phonenumber')->select()->toArray();
        $export = [];
        foreach ($data as $value) {
            $export[] = [
                $value['id'],
                $value['user_name'],
                $value['phonenumber']
            ];
        }
//        dd($export);
        // 保存文件的类型
        $type= true;
        // 设置下载文件保存的名称
        $fileName = '1910A班信息导出'.time();
        // 调用方法导出excel
        Excel::export($header,$type,$export,$fileName);
        die();
        $data = Db::table('user')->field('id,user_name,phonenumber')->select()->toArray();
        $title = ['ID', '用户名','电话'];

        // Create new Spreadsheet object
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // 方法二，使用 setCellValue
        //表头
        //设置单元格内容
        $titCol = 'A';
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }
        $row = 2; // 从第二行开始
        foreach ($data as $item) {
            $dataCol = 'A';
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValue($dataCol . $row, $value);
                $dataCol++;
            }
            $row++;
        }
        ob_end_clean();
        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="01simple.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    public function import(){
        # 导出=》 从数据库导入excel
        # 导入=》 从excel导入到数据库
        $file = \request()->file('import');

        // 将文件保存到本地
        $savename = Filesystem::disk('public')->putFile('file', $file);
        // 截取后缀
        $fileExtendName = substr(strrchr($savename, '.'), 1);
        // 有Xls和Xlsx格式两种
        if ($fileExtendName == 'xlsx') {
            $objReader = IOFactory::createReader('Xlsx');
        } else {
            $objReader = IOFactory::createReader('Xls');
        }
        // 设置文件为只读
        $objReader->setReadDataOnly(TRUE);
        // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
        $objPHPExcel = $objReader->load(public_path() . '/storage/' . $savename);
        //excel中的第一张sheet
        $sheet = $objPHPExcel->getSheet(0);
        // 取得总行数
        $highestRow = $sheet->getHighestRow();
        // 取得总列数
        $highestColumn = $sheet->getHighestColumn();
        Coordinate::columnIndexFromString($highestColumn);
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return "数据为空数组";
        }
        // 直接取出excle中的数据
        $data = $objPHPExcel->getActiveSheet()->toArray();
        dd($data);
        # 添加入库
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }


    /**
     * 七牛云上传
     */
    public function qiniu(){

        if (\request()->isPost()) {
            $image = \request()->file('file');

            $path = Filesystem::disk('qiniu')->putFile(date('Y-m-d'),$image,'uniqid');
            dd($path);
        } else{
            return View::fetch();
        }
    }
}
